
package com.fund.datacopy.bean;

import java.util.Date;

import org.apache.commons.lang.StringUtils;

import com.aug3.sys.util.DateUtil;
import com.fund.datacopy.conf.Constants;
import com.fund.datacopy.env.EnvConfigure;
import com.fund.datacopy.utils.DataCopyUtil;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;

/**
 * changqi.wu 2016年8月23日
 */

public class Coper implements Runnable {

	private Atom src;
	private Atom dest;

	public Atom getSrc() {
		return src;
	}

	public void setSrc(Atom src) {
		this.src = src;
	}

	public Atom getDest() {
		return dest;
	}

	public void setDest(Atom dest) {
		this.dest = dest;
	}

	public void copy() throws Exception {
		EnvConfigure conf = new EnvConfigure();
		conf.setUrl(src.getUrl());
		conf.setDb(src.getDb());
		conf.setTable(src.getTable());

		EnvConfigure conf2 = new EnvConfigure();
		conf2.setUrl(dest.getUrl());
		conf2.setDb(dest.getDb());
		conf2.setTable(dest.getTable());

		DBCollection conn = conf.getMongoConnection();
		DBCollection conn2 = conf2.getMongoConnection();

		String colnum = src.getCollum();
		String style = src.getStyle();
		String ext = src.getExt();

		BasicDBObject q = new BasicDBObject();

		if (StringUtils.isBlank(colnum)) {
			colnum = dest.getCollum();
		}

		if (StringUtils.isBlank(style)) {
			style = dest.getStyle();
		}

		if (StringUtils.isBlank(ext)) {
			ext = dest.getExt();
		}

		if (StringUtils.isNotBlank(colnum)) {
			if (StringUtils.isNotBlank(ext)) {
				String[] vals = ext.split(Constants.COMMA);
				q.append(colnum, new BasicDBObject("$in", vals));
			} else {
				if (StringUtils.isNotBlank(style)) {
					q.append(colnum, DateUtil.formatDate(new Date(), style));
				} else {
					q.append(colnum, DateUtil.formatDate(new Date(), Constants.DEFAULT_DT_STYLE));
				}
			}

		}
		System.out.println("start copy from " + src.getUrl() + ":" + src.getDb() + "[" + src.getTable() + "]" + " to "
				+ dest.getUrl() + ":" + dest.getDb() + "[" + dest.getTable() + "]" + " identify by " + q.toString());
		DataCopyUtil.copy(conn, conn2, q);
	}

	@Override
	public void run() {
		try {
			copy();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}
